package com.interpreter.self;

import java.util.HashMap;
import java.util.Stack;

public class Calculator {

    private Stack<Emulation> emulations= new Stack<>();

    private Emulation left;
    private Emulation right;

    private Emulation emulation;

    public void getEmulation(String expStr){
        char [] arrayStr = expStr.toCharArray();
        for(int i=0;i<arrayStr.length;i++){
            if(arrayStr[i]=='+'){
                left = emulations.pop();
                right = new VarEmulation(String.valueOf(arrayStr[++i]));
                emulations.push(new AddEmulation(left,right));
                break;
            }else if(arrayStr[i]=='-'){
                left = emulations.pop();
                right = new VarEmulation(String.valueOf(arrayStr[++i]));
                emulations.push(new SubtractEmulation(left,right));
                break;
            } else {
                emulations.push(new VarEmulation(String.valueOf(arrayStr[i])));
            }
        }
        this.emulation=emulations.pop();
    }

    public int calculate(HashMap<String,Integer> var){
        return this.emulation.intercept(var);
    }
}
